import Vue from "vue";
import Vuex from "vuex";
import * as types from "./mutations-types";
import { api_right_menus } from "../api/index";
import dynamicRouter from '../router/dynamic-router';
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    get userInfo() {
      //获取用户信息
      return JSON.parse(localStorage.getItem("userInfo"));
    },
    set userInfo(value) {
      //设置用户信息
      localStorage.setItem("userInfo", JSON.stringify(value));
    },
    get token() {
      //获取token
      return localStorage.getItem("token");
    },
    set token(value) {
      //设置token
      localStorage.setItem("token", value);
    },
    menus_rights: JSON.parse(localStorage.getItem("menus_rights"))
  },
  mutations: {
    [types.LOGIN_IN](state, payload) {
      // 登录后设置用户信息 及token
      state.userInfo = payload;
      state.token = payload.token;
    },
    [types.LOGIN_OUT](state) {
      // 退出登录后清空 用户信息 及token
      state.userInfo = "";
      state.token = "";
    },
    [types.SET_MENUS](state, payload) {
      // 设置 左侧菜单到state
      state.menus_rights = payload;
    }
  },
  actions: {
    [types.MENUS_ACTION](context) {
      // 请求菜单 提交到数据到 mutations
      api_right_menus().then(res => {
        if (res.meta.status == 200) {
          context.commit(types.SET_MENUS, res.data);
          localStorage.setItem("menus_rights", JSON.stringify(res.data)); // 把动态菜单存到storage
          res.data.forEach(parentItem => {//生成动态路由
            parentItem.children.forEach(childItem => {
              dynamicRouter(parentItem,childItem)// 调用动态路由函数
            });
          });
        } else {
          // Vue.$message.error(res.meta.msg + ",获取菜单失败");
        }
      });
    }
  },
  modules: {}
});
